import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.sql.SQLException;
import java.util.ArrayList;

/**
 * AddEditUser
 * Panel with GUI to add or edit a User
 *
 *
 *  Date           	Name            	Action
 *  --------------------------------------------------------------------------------------
 *	03/06/11		Bethany				Copied over class to new repository. added fields, getters, and setters
 *
 *
 *
 * @author bethanysumner
 * @version $Revision: 1.0 $
 */

public class AddEditUser extends JPanel {
	
	/**
	 * Field user.
	 */
	private String user;
	/**
	 * Field main.
	 */
	private MainWindow main;
	/**
	 * Field database.
	 */
	private Database database;
	
	/**
	 * Field btnCancel.
	 */
	/**
	 * Field btnUpdate.
	 */
	/**
	 * Field btnCreate.
	 */
	private JButton btnCreate, btnUpdate, btnCancel;
	/**
	 * Field txtEmail.
	 */
	/**
	 * Field txtUserName.
	 */
	/**
	 * Field txtLastName.
	 */
	/**
	 * Field txtFirstName.
	 */
	private JTextField txtFirstName, txtLastName, txtUserName, txtEmail;
	/**
	 * Field comboYear.
	 */
	/**
	 * Field comboDay.
	 */
	/**
	 * Field comboMonth.
	 */
	private JComboBox comboMonth, comboDay, comboYear;
	/**
	 * Field rdbtnSystemAdmin.
	 */
	/**
	 * Field rdbtnDoctor.
	 */
	/**
	 * Field rdbtnNurse.
	 */
	/**
	 * Field rdbtnPatient.
	 */
	/**
	 * Field rdbtnHermapherdite.
	 */
	/**
	 * Field rdbtnMale.
	 */
	/**
	 * Field rdbtnFemale.
	 */
	private JRadioButton rdbtnFemale, rdbtnMale, rdbtnHermapherdite, rdbtnPatient, rdbtnNurse, rdbtnDoctor, rdbtnSystemAdmin;
	/**
	 * Field buttonListener.
	 */
	private ButtonListener buttonListener;
	
	/**
	 * AddEditUser constructor to ADD a current User
	 * @param main A reference to the main window
	 * @param database A reference to the database
	
	 */
	public AddEditUser(MainWindow main, Database database){
		
		main.showMessage("Enter the following information to create a new user.");
		
		this.main = main;
		this.database = database;
		
		createLayout();
		
		// create ButtonListener
		buttonListener = new ButtonListener();
		btnCreate = new JButton("Create User");
		btnCreate.setBounds(160, 359, 117, 29);
		btnCreate.addActionListener(buttonListener);
		add(btnCreate);
		
	}
	
	
	/**
	 * AddEditUser constructor to edit a current user
	 * @param user The username of the user to edit.
	
	
	 * @param main MainWindow
	 * @param database Database
	 * @throws ClassNotFoundException  * @throws SQLException  */
	public AddEditUser(MainWindow main, Database database, String user){
		
		this.main = main;
		this.database = database;
		this.user = user;
		
		main.showMessage("Enter the following information to edit " + user + "'s information");
		
		createLayout();
		populatefields(); // populate fields with values from the current user
		
		// create ButtonListener
		buttonListener = new ButtonListener();
		btnUpdate = new JButton("Update User");
		btnUpdate.setBounds(160, 359, 117, 29);
		btnUpdate.addActionListener(buttonListener);
		add(btnUpdate);
		
	}
	
	/**
	 * Creates the GUI layout
	 */
	private void createLayout(){
		
		setPreferredSize(new Dimension(800, 667));
		setLayout(null);
		
		// create ButtonListener
		buttonListener = new ButtonListener();
		// make cancel button
		btnCancel = new JButton("Cancel");
		btnCancel.setBounds(31, 359, 117, 29);
		btnCancel.addActionListener(buttonListener);
		add(btnCancel);
		
		// first name field
		final JLabel lblFirstName = new JLabel("First Name:");
		lblFirstName.setBounds(41, 98, 117, 16);
		add(lblFirstName);
		txtFirstName = new JTextField();
		txtFirstName.setBounds(170, 92, 199, 28);
		add(txtFirstName);
		txtFirstName.setColumns(10);
		
		// last name field
		JLabel lblLastName = new JLabel("Last Name:");
		lblLastName.setBounds(41, 144, 102, 16);
		add(lblLastName);
		txtLastName = new JTextField();
		txtLastName.setBounds(170, 138, 199, 28);
		add(txtLastName);
		txtLastName.setColumns(10);
		
		// username field
		JLabel lblUsername = new JLabel("Username:");
		lblUsername.setBounds(41, 52, 117, 16);
		add(lblUsername);
		txtUserName = new JTextField();
		txtUserName.setColumns(10);
		txtUserName.setBounds(170, 46, 199, 28);
		add(txtUserName);
		
		// email field
		JLabel lblEmail = new JLabel("E-mail Address:");
		lblEmail.setBounds(41, 183, 117, 16);
		add(lblEmail);
		txtEmail = new JTextField();
		txtEmail.setBounds(170, 177, 199, 28);
		add(txtEmail);
		txtEmail.setColumns(10);
		
		// sex field
		JLabel lblSex = new JLabel("Sex:");
		lblSex.setBounds(41, 232, 61, 16);
		add(lblSex);
		rdbtnMale = new JRadioButton("Male");
		rdbtnMale.setBounds(170, 232, 72, 23);
		add(rdbtnMale);
		rdbtnFemale = new JRadioButton("Female");
		rdbtnFemale.setBounds(248, 232, 81, 23);
		add(rdbtnFemale);
		rdbtnHermapherdite = new JRadioButton("Hermaphrodite");
		rdbtnHermapherdite.setBounds(329, 232, 126, 23);
		add(rdbtnHermapherdite);
		ButtonGroup sexButtonGroup = new ButtonGroup();
		sexButtonGroup.add(rdbtnHermapherdite);
		sexButtonGroup.add(rdbtnMale);
		sexButtonGroup.add(rdbtnFemale);
		rdbtnFemale.setSelected(true); // Make female the default value
		
		// user type field
		ButtonGroup userTypeButtonGroup = new ButtonGroup();
		rdbtnPatient = new JRadioButton("Patient");
		rdbtnPatient.setSelected(true); //make patient the default value
		userTypeButtonGroup.add(rdbtnPatient);
		if(main.getUsertype() == 0){ //only admin can create any users besides patients
			JLabel lblUserType = new JLabel("User Type:");
			lblUserType.setBounds(41, 290, 87, 16);
			add(lblUserType);
			rdbtnPatient.setBounds(166, 286, 81, 23);
			add(rdbtnPatient);
			rdbtnNurse = new JRadioButton("Nurse");
			rdbtnNurse.setBounds(258, 286, 81, 23);
			add(rdbtnNurse);
			rdbtnDoctor = new JRadioButton("Doctor");
			rdbtnDoctor.setBounds(337, 286, 81, 23);
			add(rdbtnDoctor);
			rdbtnSystemAdmin = new JRadioButton("System Admin");
			rdbtnSystemAdmin.setBounds(420, 286, 126, 23);
			add(rdbtnSystemAdmin);
			userTypeButtonGroup.add(rdbtnNurse);
			userTypeButtonGroup.add(rdbtnDoctor);
			userTypeButtonGroup.add(rdbtnSystemAdmin);
		}
	}
	
	
	/**
	 * Populate fields based on the currentUser
	
	
	 * @throws ClassNotFoundException  * @throws SQLException  */
	private void populatefields() {
		
		txtUserName.setText(user);
		txtUserName.setEditable(false);
		txtUserName.setEnabled(false);
		
		try {
			ArrayList<String> info = database.viewUser(user);
			System.out.println("user info: " + info);
			int first = 0, last = 1, email = 4, sex = 5, type = 6; // lists index of where to find the information in the info ArrayList
			
			txtFirstName.setText(info.get(first));
			txtLastName.setText(info.get(last));
			txtEmail.setText(info.get(email));
			
			//set sex
			switch(info.get(sex).charAt(0)){
			case 'M':
				rdbtnMale.setSelected(true);
				break;
			case 'F':
				rdbtnFemale.setSelected(true);
				break;
			case 'H':
				rdbtnHermapherdite.setSelected(true);
				break;
			}
			
			// user type
			switch(info.get(type).charAt(0)){
			case '0':
				rdbtnSystemAdmin.setSelected(true);
				break;
			case '1':
				rdbtnDoctor.setSelected(true);
				break;
			case '2':
				rdbtnNurse.setSelected(true);
				break;
			case '3':
				rdbtnPatient.setSelected(true);
				break;
			}

		} catch (SQLException e) {
			e.printStackTrace();
			main.showMessage("Error getting information from database");
		}
	}
	
	/**
	 * Create a user with data from the fields
	 */
	public void createUser(){
		String message = "";
		
		//Username should be 2 - 20 characters
		if(txtUserName.getText().length() < 2 || txtUserName.getText().length() > 20){
			message += "Username should be 2 - 20 characters long. ";
		}
			
		//First name should not be blank
		if(txtFirstName.getText().length() < 1){
			message += "Please enter the first name. ";
		}	
		
		//Last name should not be blank
		if(txtFirstName.getText().length() < 1){
			message += "Please enter the last name. ";
		}
		
		//email address should not be blank
		if(txtEmail.getText().length() < 1){
			message += "Please enter the email address. ";
		}
		
		if(message.length() < 1){ //no errors -> create user
			
			String sex = "X";
			int userType = -1;	
			
			if(rdbtnMale.isSelected()){
				sex = "M";
			}else if(rdbtnFemale.isSelected()){
				sex = "F";
			}else{
				sex = "H";
			}
			
			if(rdbtnPatient.isSelected()){
				userType = 3;
			}else if(rdbtnNurse.isSelected()){
				userType = 2;
			}else if(rdbtnDoctor.isSelected()){
				userType = 1;
			}else if(rdbtnSystemAdmin.isSelected()){
				userType = 0;
			}
			
			
			try {
				if(userType == 3){
					database.addNewPatient(txtFirstName.getText(), txtLastName.getText(), txtUserName.getText(), txtLastName.getText(), txtEmail.getText(), sex);
					main.showAffirmation("Patient, " + txtUserName.getText() + ", was successfully created.");
					main.removeTab(this);
				} else{
					database.addNewUser(txtFirstName.getText(), txtLastName.getText(), txtUserName.getText(), txtLastName.getText(), txtEmail.getText(), sex, userType);
					main.showAffirmation("User, " + txtUserName.getText() + ", was successfully created.");
					main.removeTab(this);
				}
				return;
			} catch (SQLException e) {
				e.printStackTrace();
				message = "Error. Patient was not created.";
			} catch (UsernameAlreadyTakenException e) {
				message = "Username already taken";
			}
			
		}
			
		main.showError(message);
		
	}
	
	/**
	 * Update a user with the data from the fields
	 */
	private void updateUser(){
		
		String sex;
		int type;
		
		if(rdbtnMale.isSelected()){
			sex = "M";
		}else if(rdbtnFemale.isSelected()){
			sex = "F";
		}else{
			sex = "H";
		}
		
		if(rdbtnPatient.isSelected()){
			type = 3; 
		}else if(rdbtnNurse.isSelected()){
			type = 2;
		}else if(rdbtnDoctor.isSelected()){
			type = 1;
		}else{
			type = 0;
		}
		
		
		try {
			
			database.updateUser(this.user, txtFirstName.getText(), txtLastName.getText(), txtEmail.getText(), sex, type);
			
			main.showAffirmation("User, " + this.user + ", has been successfully updated.");
			main.removeTab(this);
		} catch (SQLException e) {
			main.showError("Error updating patient information");
			e.printStackTrace();
		}
		
	}
	
	/**
	 * Cancels the changes, closes the panel
	 */
	private void cancel(){
		main.showMessage("Add user canceled");
		main.removeTab(this);
	}
	
	
	/**
	 * ButtonListener
	 * ActionListener to listen when button has been pressed
	 *
	 *
	 *  Date           	Name            	Action
	 *  --------------------------------------------------------------------------------------
	 *	03/06/11		Bethany				Created Class
	 *
	 *
	 *
	 * @author bethanysumner
	 * @version 1.0
	 */
	private class ButtonListener implements ActionListener{
		
		/**
		 * Performs tasks corresponding to the action
		 * @param event The action event
		 * @see java.awt.event.ActionListener#actionPerformed(ActionEvent)
		 */
		public void actionPerformed(ActionEvent event){
			
			if(event.getSource().equals(btnCreate)){
				createUser();
			}else if(event.getSource().equals(btnUpdate)){
				updateUser();
			}else if(event.getSource().equals(btnCancel)){
				cancel();
			}
			
		}
		
	}// end ButtonListener
}
